package cn.witsky.rtp2ws.util;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class SignUtils {
	public static String signature(Map<String, String> params,List<String> removeKeyList,String secret) {
		String result = null;
		if (params == null)
			return result;
		// 1. 把字典按Key的字母顺序排序
		Map<String, String> treeMap = new TreeMap<String, String>();
		treeMap.putAll(params);
		if(removeKeyList!=null) {
			for(String key:removeKeyList) {
				treeMap.remove(key);
			}
		}		
		// 3 把参数串起来
		Iterator<String> iter = treeMap.keySet().iterator();
		StringBuffer orgin = new StringBuffer(secret);
		while (iter.hasNext()) {
			String name = (String) iter.next();
			try {
				orgin.append(name).append(treeMap.get(name));
			} catch (Exception e) {
				System.out.println("！！！！！！！" + name + "==");
			}

		}
		// 4. 加密：MD5 + 大写&十六进制
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception e) {
			throw new RuntimeException("sign error !");
		}
		return result;
	}
    private static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

}
